package ar.com.jwa.services.impl;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

import ar.com.jwa.domain.User;
import ar.com.jwa.services.UserLocalService;

public class UserLocalServiceImpl implements UserLocalService {

	private EntityManager em;
	
	private static final Log log = LogFactory.getLog(UserLocalServiceImpl.class);
	
	@Transactional
	public void saveUser(User user) {
		log.error("saving user");
		em.persist(user);
	}
	
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@Override
	public boolean login(User user) {
		Collection<User> array = em.createQuery("select U FROM ar.com.jwa.domain.User U where U.nickName='" + user.getEmail().trim()+ "' and U.password ='"+ user.getPassword()+"'").getResultList();
		return array.size() == 1;
	}

	@Override
	public User getUserById(Long id) {
		User user = (User) em.createQuery("select U FROM ar.com.jwa.domain.User U where U.id=" +id).getSingleResult();
		if ( user!= null )
			return user;
		return null;
	}
}
